package cn.acrdpm.tools;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;

/**
 *  消息转化类
 * @author 张敏
 * @date 2021/3/14
 */
public class MessageHelper {

    public static Message objToMsg(Object obj) {
        if (null == obj) {
            return null;
        }

        Message message = MessageBuilder.withBody(JsonUtils.toJson(obj).getBytes()).build();
        // 消息持久化:默认是持久化的可以不用设置
        message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
        //消息投递格式：默认是 application/octet-stream 添加 消息转化器之后默认为：application/json 格式
        message.getMessageProperties().setContentType(MessageProperties.CONTENT_TYPE_JSON);
        return message;
    }

    public static <T> T msgToObj(Message message, Class<T> clazz) {
        if (null == message || null == clazz) {
            return null;
        }
        T obj = JsonUtils.parseToObject(new String(message.getBody()), clazz);

        return obj;
    }
}
